from threading import Thread, Event


class RepeatingTimer(Thread):
    """
    定时执行程序
    """
    def __init__(self, interval, function, daemon=None, args=None, kwargs=None):
        Thread.__init__(self, daemon=daemon)
        self.interval = interval
        self.function = function
        self.args = args if args is not None else []
        self.kwargs = kwargs if kwargs is not None else {}
        self.finished = Event()

    def cancel(self):
        """Stop the timer if it hasn't finished yet."""
        self.finished.set()

    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)

if __name__ == "__main__":
    def printf(num):
        print(num)
    t = RepeatingTimer(0.1, printf, (666,))
    t.start()

    t.cancel()